package server

import (
	"fmt"
	"mcp-clarification-service/pkg/logger"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// startGUIServiceProcess 启动 GUI 服务进程
func startGUIServiceProcess(log *logger.Logger) error {
	// 获取可执行文件路径
	exePath, err := os.Executable()
	if err != nil {
		return fmt.Errorf("failed to get executable path: %w", err)
	}

	// 获取可执行文件所在目录
	exeDir := filepath.Dir(exePath)

	// 构建 GUI 服务可执行文件路径
	var guiServerPath string
	if runtime.GOOS == "windows" {
		guiServerPath = filepath.Join(exeDir, "gui-server.exe")
	} else {
		guiServerPath = filepath.Join(exeDir, "gui-server")
	}

	// 检查文件是否存在
	if _, err := os.Stat(guiServerPath); os.IsNotExist(err) {
		return fmt.Errorf("GUI server executable not found: %s", guiServerPath)
	}

	log.Info("Starting GUI service: %s", guiServerPath)

	// 启动进程
	cmd := exec.Command(guiServerPath)

	// 设置进程属性（后台运行）
	if runtime.GOOS == "windows" {
		// Windows: 隐藏窗口
		cmd.SysProcAttr = getWindowsHiddenProcAttr()
	} else {
		// Unix: 分离进程
		cmd.SysProcAttr = getUnixDetachedProcAttr()
	}

	// 启动进程
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("failed to start GUI service: %w", err)
	}

	log.Info("GUI service started with PID: %d", cmd.Process.Pid)

	return nil
}
